package day5.phenomenons;

/**
 * 加锁方式七：与锁的类型无关，任何类型的对象都可以作为锁
 * 加锁成功
 */
public class Demo7 {

    // 定义一个被操作的数
    static int r = 0;
    // 定义操作的数
    static final int COUNT = 1000_0000;

    static class Add extends Thread {

        String o;
        Add(String o) {
            this.o = o;
        }

        @Override
        public void run() {
            synchronized (o) {
                for (int i = 0; i < COUNT; i++) {
                    r++;
                }
            }
        }
    }

    static class Sub extends Thread {

        String o;
        Sub(String o) {
            this.o = o;
        }

        @Override
        public void run() {
            synchronized (o) {
                for (int i = 0; i < COUNT; i++) {
                    r--;
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {

        String o = "锁";

        Thread add = new Add(o);
        add.start();
        Thread sub = new Sub(o);
        sub.start();

        // 等待结束
        add.join();
        sub.join();
        
        System.out.println(r);
    }
}
